/**
 * 实现一个线程池，最多能同时执行 5 个异步任务，每当有一个任务完成时即可再推入一个任务
 * 
 * 1. 定义结果result[]
 * 2. 遍历数组，调用对应函数，在函数的.then俩
 */

class ThreadPool {
  constructor(worker) {
    this.worker = worker
    this.taskQueue = []
    this.running = 0

  }
  // 添加之后就直接调用run方法
  addTask (task) {
    this.taskQueue.push(task)
    this.runNextTask()
  }
  runNextTask () {
    if (this.running < this.worker && this.taskQueue.length > 0) {
      this.running++
      const currentTask = this.taskQueue.shift()
      currentTask()
        .finally(() => {
          this.running--
          this.runNextTask()
        })
    }
  }
}

const threadPool = new ThreadPool(5)

// 模拟异步任务  
const asyncTask = (id, wait) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(`Task ${id} completed`)
      resolve()
    }, wait)
  })
}

for (let i = 0; i < 50; i++) {
  threadPool.addTask(() => asyncTask(i + 1, Math.floor(Math.random() * 1000)))
}
// threadPool.addTask(() => asyncTask(1, 1000))
// threadPool.addTask(() => asyncTask(2, 5000))
// threadPool.addTask(() => asyncTask(3, 3000))
// threadPool.addTask(() => asyncTask(4, 4000))
// threadPool.addTask(() => asyncTask(5, 5000))